import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/widget/group_text_filed.dart';
import 'package:image_pickers/image_pickers.dart';

class CommentInputView extends StatefulWidget {
  static const String routeName = 'comment_input';
  final String? hint;
  final TextEditingController textEditController;
  final String? selectedImgPath;
  final Function(String? imgPath)? imgCallback;

  CommentInputView({
    super.key,
    this.hint,
    required this.textEditController,
    this.selectedImgPath,
    this.imgCallback,
  });

  @override
  State<CommentInputView> createState() => _CommentInputViewState();
}

class _CommentInputViewState extends State<CommentInputView> with WidgetsBindingObserver {
  final focus = FocusNode();

  TextEditingController get textEditController => widget.textEditController;
  bool hasShowKeyboard = false;
  bool isImageSelectIng = false;
  String? selectedImgPath;

  @override
  void initState() {
    super.initState();
    selectedImgPath = widget.selectedImgPath;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      focus.requestFocus();
    });
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // print(MediaQuery.of(context).viewInsets.bottom);
      if (MediaQuery.of(context).viewInsets.bottom == 0) {
        if ((Get.isBottomSheetOpen ?? false) && hasShowKeyboard && !isImageSelectIng) {
          // if (hasShowKeyboard && mounted) {
          hasShowKeyboard = false;
          // Get.back();
          // }
        }
      } else {
        hasShowKeyboard = true;
      }
    });
  }

  void choseImg() async {
    isImageSelectIng = true;
    final listMedia = await ImagePickers.pickerPaths(
      uiConfig: UIConfig(uiThemeColor: Colors.white),
      galleryMode: GalleryMode.image,
      selectCount: 1,
      showCamera: false,
    );
    if (listMedia.isNotEmpty) {
      final ret = listMedia.map((e) => e.path ?? '').toList();
      selectedImgPath = ret.first;
      widget.imgCallback?.call(selectedImgPath!);
    }
    setState(() {});
    Future.delayed(Duration(milliseconds: 500), () {
      isImageSelectIng = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: () {
          Get.back();
        },
        child: Container(
          alignment: Alignment.bottomCenter,
          child: GestureDetector(
            onTap: (){},
            child: Container(
              color: Colors.black,
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  if (selectedImgPath?.isNotEmpty == true)
                    Container(
                      margin: EdgeInsets.only(bottom: 12),
                      width: 60,
                      height: 60,
                      child: Stack(
                        fit: StackFit.expand,
                        children: [
                          Image.file(
                            File(selectedImgPath!),
                            width: 60,
                            height: 60,
                            fit: BoxFit.cover,
                          ),
                          Positioned(
                            top: 0,
                            right: 6,
                            child: GestureDetector(
                              onTap: () {
                                selectedImgPath = null;
                                widget.imgCallback?.call(null);
                                setState(() {});
                              },
                              child: Image.asset(
                                "close_grey.png".commonImgPath,
                                width: 12,
                                height: 12,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  Row(
                    children: [
                      Expanded(
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 2),
                          child: GroupTextFiled(
                            focusNode: focus,
                            controller: textEditController,
                            height: 32,
                            padding: EdgeInsets.symmetric(horizontal: 16),
                            textStyle: TextStyle(color: Colors.white, fontSize: 14),
                            onSubmitted: (value) {
                              Get.back(result: true);
                            },
                            placeholder: widget.hint ?? '请在此输入评论',
                            placeholderTextStyle: TextStyle(color: Color(0xff4D4D4D), fontSize: 14),
                            decoration: BoxDecoration(color: Color(0xff1A1A1A), borderRadius: BorderRadius.circular(40)),
                          ),
                        ),
                      ),
                      12.sizeBoxW,
                      Stack(
                        children: [
                          Container(
                            margin: EdgeInsets.only(right: 12, top: 4, bottom: 4),
                            child: GestureDetector(
                              onTap: choseImg,
                              child: Image.asset(
                                'icon_pic.webp'.commentPath,
                                width: 30,
                                height: 30,
                              ),
                            ),
                          ),
                        ],
                      ),
                      GestureDetector(
                        onTap: () {
                          if (textEditController.text.isEmpty) {
                            showToast('请输入想要说的话哦～～');
                            return;
                          }
                          Get.back(result: true);
                        },
                        child: Image.asset(
                          'ic_send.webp'.commentPath,
                          width: 30,
                          height: 30,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          )
        ),
      ),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}
